package com.hy.mvc.biz.excel.convert;

import com.hy.mvc.biz.excel.anotation.DateTransform;
import com.hy.mvc.biz.utils.ReflectionUtils;
import org.apache.commons.lang.StringUtils;

import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Booker on 2017/7/3.
 */
public class DateTransformer implements ICellDataTransformer {
    @Override
    public String convert(Field field, Object exportObj) {
        Date date = (Date) ReflectionUtils.getFieldValue(exportObj, field.getName());
        DateTransform dateTransform = field.getAnnotation(DateTransform.class);

        if (date == null) {
            return null;
        }

        String pattern = StringUtils.EMPTY;
        if (dateTransform != null) {
            pattern = dateTransform.value();
        }

        if (StringUtils.isBlank(pattern)) {
            pattern = "yyyy-MM-dd";
        }

        DateFormat df = new SimpleDateFormat(pattern);
        return df.format(date);
    }

}
